<?php

namespace AdminBundle\Controller;

use AdminBundle\Entity\AuthGroup;
use AdminBundle\Entity\AuthLinkGroupRoles;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Method;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Component\Config\Definition\Exception\Exception;
use Symfony\Component\HttpFoundation\Request;
use AdminBundle\Utility\Constant;

/**
 * Authgroup controller.
 *
 * @Route("authgroup")
 */
class AuthGroupController extends BaseController
{
    /**
     * Lists all authGroup entities.
     *
     * @Route("/", name="authgroup_index")
     * @Method("GET")
     */
    public function indexAction(Request $request)
    {
        $page = $request->get("page");
        $page = is_numeric($page) ? $page : 1;
        $keyword = $request->get('keyword');
        $date_range = $request->get('date_range');
        $starttime = $request->get('starttime');
        $endtime = $request->get('endtime');

        $starttime = $starttime ? $starttime : date("Y-m-d", strtotime("-1 day"));
        $endtime = $endtime ? $endtime : date("Y-m-d", strtotime("+1 day"));

        $params = ['keyword' => $keyword, 'starttime' => $starttime, 'endtime' => $endtime];

        $result = $this->getDoctrine()->getRepository('AdminBundle:AuthGroup')->pageQuery($params, $page);

        return $this->render('AdminBundle:authgroup:index.html.twig', array_merge([
            'authGroups' => $result['list'],
            'querystring' => http_build_query($params),
            'page' => $result['page'],
        ], $params));

        $em = $this->getDoctrine()->getManager();

        $authGroups = $em->getRepository('AdminBundle:AuthGroup')->findAll();

        return $this->renderWithRole($request, 'AdminBundle:authgroup:index.html.twig', array(
            'authGroups' => $authGroups,
        ));
    }

    /**
     * Creates a new authGroup entity.
     *
     * @Route("/new", name="authgroup_new")
     * @Method({"GET", "POST"})
     */
    public function newAction(Request $request)
    {
        if ($request->getMethod() == "POST") {
            $auth_group = $request->request->get('auth_group');
            if (!isset($auth_group['name']) || empty($auth_group['name'])) {
                throw  new \Exception('null');
            }
            $authGroup = new AuthGroup();
            $authGroup->setName($auth_group['name']);
            $authGroup->setNote($auth_group['note']);
            $authGroup->setIsEnabled(isset($auth_group['isEnabled']) ? true : false);
            $authGroup->setCtime(new \DateTime());
            $authGroup->setCreateUser($this->getUser()->getUsername());

            $em = $this->getDoctrine()->getManager();
            $em->persist($authGroup);
            $em->flush();

            $this->assignRole($request,$authGroup);

            return $this->redirectToRoute('authgroup_index');
        }

        $authRoles = $this->getDoctrine()->getRepository('AdminBundle:AuthRole')->loadGroupRoles();

        return $this->renderWithRole($request, 'AdminBundle:authgroup:new.html.twig', array(
            'authRoles' => $authRoles,
        ));
    }

    public function assignRole(Request $request, AuthGroup $authGroup)
    {
        // 设置组的角色
        $roles = [];
        $auth_group = $request->request->get('auth_group', []);

        if (isset($auth_group['role']) && !empty($auth_group['role'])) {
            $em = $this->getDoctrine()->getManager();
            $roles = $auth_group['role'];
            foreach ($roles as $roleId) {
                // 滤重
                $obj_is_exists = $em->getRepository('AdminBundle:AuthGroup')->loadByGroupIdAndRoleId(
                    $authGroup->getId(), trim($roleId)
                );
                if ($obj_is_exists != null)
                    continue;

                $authRole = $em->getRepository('AdminBundle:AuthRole')->findOneBy(['id' => $roleId]);

                $authLinkGroupRoles = new AuthLinkGroupRoles();
                $authLinkGroupRoles->setGroup($authGroup);
                $authLinkGroupRoles->setRole($authRole);
                $authLinkGroupRoles->setCtime(new \DateTime());
                $authLinkGroupRoles->setCreateUser($this->getUser()->getUsername());
                $em->persist($authLinkGroupRoles);
            }
            $em->flush();
        }
        return $roles;
    }

    /**
     * Finds and displays a authGroup entity.
     *
     * @Route("/{id}", name="authgroup_show")
     * @Method("GET")
     */
    public function showAction(Request $request, AuthGroup $authGroup)
    {
        $deleteForm = $this->createDeleteForm($authGroup);

        return $this->renderWithRole($request, 'AdminBundle:authgroup:show.html.twig', array(
            'authGroup' => $authGroup,
            'delete_form' => $deleteForm->createView(),
        ));
    }

    /**
     * Displays a form to edit an existing authGroup entity.
     *
     * @Route("/{id}/edit", name="authgroup_edit")
     * @Method({"GET", "POST"})
     */
    public function editAction(Request $request, AuthGroup $authGroup)
    {
        $deleteForm = $this->createDeleteForm($authGroup);
        $editForm = $this->createForm('AdminBundle\Form\AuthGroupType', $authGroup, Constant::FORM_ATTR_CLASS);
        $editForm->handleRequest($request);

        if ($editForm->isSubmitted() && $editForm->isValid()) {

            $this->getDoctrine()->getManager()->flush();

            $roleIds = $this->assignRole($request, $authGroup);
            $ret = $this->getDoctrine()->getRepository('AdminBundle:AuthGroup')->revokeGroupRole($authGroup->getId(), $roleIds);

            return $this->redirectToRoute('authgroup_edit', array('id' => $authGroup->getId()));
        }
        $authRoles = $this->getDoctrine()->getRepository('AdminBundle:AuthRole')->loadGroupRoles($authGroup->getId());
        return $this->renderWithRole($request, 'AdminBundle:authgroup:edit.html.twig', array(
            'authGroup' => $authGroup,
            'form' => $editForm->createView(),
            'delete_form' => $deleteForm->createView(),
            'authRoles' => $authRoles,
        ));
    }

    /**
     * Deletes a authGroup entity.
     *
     * @Route("/{id}", name="authgroup_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, AuthGroup $authGroup)
    {
        $form = $this->createDeleteForm($authGroup);
        $form->handleRequest($request);

        if ($form->isSubmitted() && $form->isValid()) {
            $em = $this->getDoctrine()->getManager();

            $ret = $em->getRepository('AdminBundle:AuthGroup')->revokeGroupRole($authGroup->getId());

            $em->remove($authGroup);
            $em->flush();
        }

        return $this->redirectToRoute('authgroup_index');
    }

    /**
     * Creates a form to delete a authGroup entity.
     *
     * @param AuthGroup $authGroup The authGroup entity
     *
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(AuthGroup $authGroup)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('authgroup_delete', array('id' => $authGroup->getId())))
            ->setMethod('DELETE')
            ->getForm();
    }
}
